package com.info3k.client.tabs;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.info3k.client.Info3K;
import com.info3k.client.commands.event.ShowEventCommand;
import com.info3k.client.components.InfoWindow;
import com.info3k.client.domain.Event;
import com.info3k.client.enums.TabTypes;

public class LatestEvents extends Tab{

	private int size;
	
	private VerticalPanel panel = new VerticalPanel();
	
	private HTML html = new HTML("<h2>" + Info3K.msgs.latest1() + " " + Info3K.msgs.events() + "</h2>");
	
	private Map<Hyperlink, Event> addressesMap = new HashMap<Hyperlink, Event>();
	
	private List<Event> tabContent;

	public LatestEvents(int size) {
		this.size = size;
		initWidget(panel);
		refresh();
	}
	
	@Override
	public void refresh(){
		panel.clear();
		panel.add(html);
		panel.add(new HTML("<br><br>" + Info3K.msgs.loading() + "..."));
		
		infoService.getLatestEvents(size, new AsyncCallback<List<Event>>(){
			public void onFailure(Throwable caught) {
				Info3K.loader.setVisible(false);
				InfoWindow.showMessage(Info3K.msgs.error(), caught.getMessage());
			}

			public void onSuccess(List<Event> result) {
				Info3K.loader.setVisible(false);
				tabContent = result;
				render();
			}
		});
	}
	
	@Override
	public void render() {
		panel.clear();
		panel.add(html);
		int i = 1;
		for (Event event : tabContent) {
			String a = event.getTitle();
			String sub = a;
			if(sub.length()>20) sub = sub.substring(0, 20) + "...";
			Hyperlink widget = new Hyperlink(i + ". " + sub, "");
			widget.setTitle(a);
			widget.setStylePrimaryName("latest_entities");
			widget.addClickHandler(new ClickHandler(){
				public void onClick(ClickEvent event) {
					ShowEventCommand cmd = new ShowEventCommand(RootPanel.get("right_section"), getInfo3k(), addressesMap.get(event.getSource()));
					cmd.execute();
				}
			});
			addressesMap.put(widget, event);
			panel.add(widget);
			i++;
		}
	}
	
	public void setSize(int size) {
		this.size = size;
	}

	public int getSize() {
		return size;
	}
}